﻿using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Drawing2D;

namespace LvcChong
{
    public partial class FormPromotionQuery : Form
    {
        private BindingList<PromotionListOutput> _sourcePromotion = new BindingList<PromotionListOutput>();
        private BindingList<PromotionUserListOutput> _sourceRelationUser = new BindingList<PromotionUserListOutput>();
        ModalPanelManager _modalPanelManager = new ModalPanelManager();
        private LayerHelper _layerHelper = new LayerHelper();

        public FormPromotionQuery()
        {
            InitializeComponent();
            pagerPromotion.OnPageChanged += PagerPromotion_OnPageChanged;
            pagerPromotion.OnPageSizeChanged += PagerPromotion_OnPageSizeChanged;
            pagerRelationUser.OnPageChanged += PagerRelationUser_OnPageChanged;
            pagerRelationUser.OnPageSizeChanged += PagerRelationUser_OnPageSizeChanged;

            InitPromotionGridLayout();
            InitRelationUserGridLayout();

            InitData();
        }

        private void PagerRelationUser_OnPageSizeChanged(object? sender, EventArgs e)
        {
            pagerRelationUser.Tag = null;
        }

        private void PagerPromotion_OnPageSizeChanged(object? sender, EventArgs e)
        {
            pagerPromotion.Tag = null;
        }

        private void PagerPromotion_OnPageChanged(object? sender, EventArgs e)
        {
            RefreshPromotionData();
        }

        private void PagerRelationUser_OnPageChanged(object? sender, EventArgs e)
        {
            var item = gridPromotion.ActiveRow.ListObject as PromotionListOutput;
            if (item == null) return;

            RefreshRelationUserData(item.id.ParseToLong());
        }

        private void InitPromotionGridLayout()
        {
            gridPromotion.InitializeRow += (s, e) =>
            {
                var item = e.Row.ListObject as PromotionListOutput;
                if (item == null) return;

                if (item.eventStartTime.ParseToLong(0) != 0)
                {
                    var time = item.eventStartTime.ParseToLong().ToDateTimeFromMilliseconds();
                    if (time != null)
                        e.Row.Cells[nameof(PromotionListOutput.eventStartTime)].Value = time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                }
                else if (item.eventEndTime.ParseToLong(0) != 0)
                {
                    var time = item.eventEndTime.ParseToLong().ToDateTimeFromMilliseconds();
                    if (time != null)
                        e.Row.Cells[nameof(PromotionListOutput.eventEndTime)].Value = time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                }
            };

            gridPromotion.AfterRowActivate += (s, e) =>
            {
                if (gridPromotion.ActiveRow == null) return;
                var item = gridPromotion.ActiveRow.ListObject as PromotionListOutput;
                if (item == null) return;

                RefreshRelationUserData(item.id.ParseToLong());
            };

            var displayCol = new List<UltraGridDisplayItem> {
                new UltraGridDisplayItem{ Key=nameof(PromotionListOutput.id), Caption="活动编号", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(PromotionListOutput.estateName), Caption="小区名称", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(PromotionListOutput.discountType), Caption="优惠类型", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(PromotionListOutput.discount), Caption="服务费优惠折扣", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(PromotionListOutput.limitType), Caption="活动限定人员", Position=2,ColumnWidth =180},
                new UltraGridDisplayItem{ Key=nameof(PromotionListOutput.status), Caption="活动状态", Position=2,ColumnWidth =180},
                new UltraGridDisplayItem{ Key=nameof(PromotionListOutput.eventStartTime), Caption="活动开始时间", Position=2,ColumnWidth =180},
                new UltraGridDisplayItem{ Key=nameof(PromotionListOutput.eventEndTime), Caption="活动结束时间", Position=2,ColumnWidth =180},
            };

            gridPromotion.SetDataBinding(_sourcePromotion, null);
            UltraGridHelper.InitializeUltraGridDisplay(gridPromotion, displayCol, true, new UltraGridOptions
            {
                EnableFixedHeader = true,
                EnableExport = true,
                ShowSummary = true,
                EnableFilter = true,
            });

            gridPromotion.DisplayLayout.NoDataSourceMessageEnabled = Infragistics.Win.DefaultableBoolean.False;
            gridPromotion.DisplayLayout.AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.None;

            gridPromotion.DisplayLayout.Bands[0].Columns[nameof(PromotionListOutput.discountType)].SetColumnValueList(ValueListAssist.EnumToValueList(typeof(DiscountType)));
            gridPromotion.DisplayLayout.Bands[0].Columns[nameof(PromotionListOutput.limitType)].SetColumnValueList(ValueListAssist.EnumToValueList(typeof(LimitType)));
            gridPromotion.DisplayLayout.Bands[0].Columns[nameof(PromotionListOutput.status)].SetColumnValueList(ValueListAssist.EnumToValueList(typeof(PromotionStatus)));

            gridPromotion.DisplayLayout.Override.RowAlternateAppearance.BackColor = Color.FromArgb(244, 244, 244);
        }

        private void InitRelationUserGridLayout()
        {

            grid.ClickCell += (s, e) =>
            {
                if (e.Cell.Column.Key == nameof(PromotionUserListOutput.value))
                {
                    // 通过手机号查询用户编号
                    var input = new UserInfoInput
                    {
                        page = 1,
                        limit = 10,
                        queryType = 2,
                        queryValue = e.Cell.Value.ToString(),
                    };

                    var ret = GlobalContext.DataProvider.UserInfoQuery(input);
                    if (ret != null && ret.Data != null && ret.Data.Count > 0)
                    {
                        _modalPanelManager.Show(this, new ControlUserOrderQuery(ret.Data.First().id.ToString()), closeOnOutsideClick: true);
                    }
                    else MessageHelper.ShowInfomationBox("没有查到该用户");
                }
            };

            var displayCol = new List<UltraGridDisplayItem> {
                new UltraGridDisplayItem{ Key=nameof(PromotionUserListOutput.promotionId), Caption="活动编号", Position=2,ColumnWidth =180},
                new UltraGridDisplayItem{ Key=nameof(PromotionUserListOutput.type), Caption="优惠类型", Position=2,ColumnWidth =100},
                new UltraGridDisplayItem{ Key=nameof(PromotionUserListOutput.value), Caption="手机号", Position=2,ColumnWidth =120},
            };

            grid.SetDataBinding(_sourceRelationUser, null);
            UltraGridHelper.InitializeUltraGridDisplay(grid, displayCol, true, new UltraGridOptions
            {
                EnableFixedHeader = true,
                EnableExport = true,
                ShowSummary = true,
                EnableFilter = true,
            });

            grid.DisplayLayout.NoDataSourceMessageEnabled = Infragistics.Win.DefaultableBoolean.False;
            grid.DisplayLayout.AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.None;

            grid.DisplayLayout.Bands[0].Columns[nameof(PromotionUserListOutput.type)].SetColumnValueList(ValueListAssist.EnumToValueList(typeof(DiscountType)));
            grid.DisplayLayout.Bands[0].Columns[nameof(PromotionUserListOutput.value)].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.URL;

            grid.DisplayLayout.Override.RowAlternateAppearance.BackColor = Color.FromArgb(244, 244, 244);
        }

        private void InitData()
        {
            cboQueryType.SetDataSource(typeof(DiscountType).EnumToNameValues(true), "Caption");
            cboQueryType.SelectedIndex = 0;

            dtStart.Value = null;
            dtEnd.Value = null;
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            RefreshPromotionData();
        }

        private async void RefreshPromotionData()
        {
            var input = new PromotionListInput
            {
                page = pagerPromotion.CurrentPageNo,
                limit = pagerPromotion.PageSize,
                fromPage = pagerPromotion.CurrentPageNo - 1 <= 0 ? null : pagerPromotion.CurrentPageNo - 1,
                leastTotal = pagerPromotion.TotalRecords == 0 ? null : pagerPromotion.TotalRecords,
                deepPageTokenArr = pagerPromotion.Tag?.ToString(),
                discountType = (int?)((DiscountType?)cboQueryType.SelectedItem?.DataValue),
                eventDateRange = (dtStart.Value != null && dtEnd.Value != null) ? $"{dtStart.DateTime.ToString("yyyy-MM-01")} ~ {dtEnd.DateTime.ToString("yyyy-MM-dd")}" : null
            };

            var ret = await LayerRefreshAsync(() => GlobalContext.DataProvider.PromotionListQuery(input));

            _sourcePromotion.Clear();
            if (ret != null && ret.Data != null)
            {
                if (pagerPromotion.Tag == null)
                    pagerPromotion.Tag = ret.OtherMap?.deepPageToken;
                else pagerPromotion.Tag = pagerPromotion.Tag + "," + ret.OtherMap?.deepPageToken;
                pagerPromotion.RefreshPageData(ret.Count);
                foreach (var item in ret.Data) _sourcePromotion.Add(item);
            }
        }

        private async void RefreshRelationUserData(long promotionId)
        {
            var input = new PromotionUserListInput
            {
                page = pagerRelationUser.CurrentPageNo,
                limit = pagerRelationUser.PageSize,
                fromPage = pagerRelationUser.CurrentPageNo - 1 <= 0 ? null : pagerRelationUser.CurrentPageNo - 1,
                leastTotal = pagerRelationUser.TotalRecords == 0 ? null : pagerRelationUser.TotalRecords,
                deepPageTokenArr = pagerRelationUser.Tag?.ToString(),
                promotionId = promotionId
            };

            var ret = await LayerRefreshAsync(() => GlobalContext.DataProvider.PromotionUserListQuery(input));

            _sourceRelationUser.Clear();
            if (ret != null && ret.Data != null)
            {
                if (pagerRelationUser.Tag == null)
                    pagerRelationUser.Tag = ret.OtherMap?.deepPageToken;
                else pagerRelationUser.Tag = pagerRelationUser.Tag + "," + ret.OtherMap?.deepPageToken;
                pagerRelationUser.RefreshPageData(ret.Count);
                foreach (var item in ret.Data) _sourceRelationUser.Add(item);
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            cboQueryType.SelectedIndex = 0;
            dtStart.Value = null;
            dtEnd.Value = null;
        }

        private Task<T> LayerRefreshAsync<T>(Func<T> action)
        {
            var ret = Task.Run(() =>
            {
                try
                {
                    plQuery.UpdateUI(() => plQuery.Enabled = false);
                    _layerHelper.ShowOpaqueLayer(plGrid, 30);
                    return action();
                }
                finally
                {
                    _layerHelper.HideOpaqueLayer();
                    plQuery.UpdateUI(() => plQuery.Enabled = true);
                }
            });
            return ret;
        }
    }
}